<?php
namespace app\api\controller;
use app\common\model\Sms as SmsModel;
class Sms extends Base
{
  public function sendCode () {
    $input = input();
    if(!$input['mobile']) {
      $this->ajax(202,'手机号为空');
    }
    if(!checkMobile($input['mobile'])) {
      $this->ajax(202,'手机号错误');
    }

      $user_where['mobile']=$input['mobile'];
      $user_where['mall_id']=$this->mall_id;
      $user=\app\common\model\User::getOne($user_where,'id');
      if($user && $user['id']!=$this->uid){
          $this->ajax(202,'该手机号码在该商城已被注册请换一个');
      }

      $sms = [
      'uid' => $this->uid,
      'mall_id' => $this->mall_id,
      'mobile' => $input['mobile'],
      'code' => rand(100000,999999),
      'create_time' => time()
    ];
    $id = SmsModel::insertGetId($sms);
    $res = SmsModel::sendCode($sms['mobile'],$sms['code']);
    //$res = true;
    if($res===true) { 
      cache("alisms-code-{$this->uid}-{$sms['mobile']}",$sms['code'],15*60);
      SmsModel::where('id',$id)->update(['status'=>1]);
      $this->ajax(200,'已发送');
    }else{
      $this->ajax(202,$res);
    }
  }
}